const csv = require('csvtojson');
const fs = require('fs');
const axios = require('axios')


const metricsTypeArr_zhiKaDingDan = ["normalEntity", "resaleEntity", "superSIMEntity", "normalWhite", "superSIMWhite",
    "halfWhite", "snsdESIM", "snmdESIM"
]



let bodyTemp_zhiKaDingDan = [
    {
        name: "msisdn_order_month_total",
        type: "gauge",
        metricsLabels: [
            {
                labelName: "provinceCode",
                labelValue: "451"
            },
            {
                labelName: "nodeId",
                labelValue: "DB451"
            },
            {
                labelName: "year",
                labelValue: "2022"
            },
            {
                labelName: "month",
                labelValue: "11"
            },
            {
                labelName: "orderType",
                labelValue: "normalEntity"
            }
        ],
        value: 5000
    },

    {
        name: "msisdn_order_month_make_total",
        type: "gauge",
        metricsLabels: [
            {
                labelName: "provinceCode",
                labelValue: "451"
            },
            {
                labelName: "nodeId",
                labelValue: "DB451"
            },
            {
                labelName: "year",
                labelValue: "2022"
            },
            {
                labelName: "month",
                labelValue: "11"
            },
            {
                labelName: "orderType",
                labelValue: "normalEntity"
            }
        ],
        value: 3000
    }
];

async function readDataFromCsv(filePath) {
    return csv().fromFile(filePath)
        .subscribe(json => {
            return new Promise((resolve, reject) => {
                if (!json) {
                    reject('read csv error')
                } else {
                    resolve(json)
                }
            })
        })
}



async function sendMetrics_zhiKaDingDan(orderType, nodeId, provinceCode) {
    
    
    

}

function genValueByType( sourceValue) {
    let tmp = Math.floor(Math.random() * 3) * 10;
    let r = 15000;
    r = r + sourceValue + tmp
    return r;
}




async function batchSendMetrics(year, month, day) {
    

    
    nodeList.filter(x => {
        if (!nodeId || nodeId ==='') {
            return true;
        } else {
            return nodeId == x.code;
        }
    }).forEach(nodeInfo => {
        let provinceList = nodeInfo.province.split(',');
        provinceList.filter(x => {
            if (!provinceCode || provinceCode == "") {
                return true;
            } else {
                return x == provinceCode;
            }
        }).forEach(p => {
            console.log(nodeInfo.code, p)
            metricsTypeArr_zhiKaDingDan.forEach(  orderType => {
                let bodyTemp_zhiKaDingDan_tmp = JSON.parse(JSON.stringify(bodyTemp_zhiKaDingDan))
                for (let i = 0; i < bodyTemp_zhiKaDingDan_tmp.length; i++) {
                    let item = bodyTemp_zhiKaDingDan_tmp[i]
                    for (let j = 0; j < item.metricsLabels.length; j++) {
                        let y = item.metricsLabels[j];
                        if (y.labelName == "month") {
                            y.labelValue = month;
                        }
                        if (y.labelName == "year") {
                            y.labelValue = year;
                        }
                        if (y.labelName == "orderType") {
                            y.labelValue = orderType;
                        }
                        if (y.labelName == "provinceCode") {
                            y.labelValue = p;
                        }
                        if (y.labelName == "nodeId") {
                            y.labelValue = nodeInfo.code;
                        }
                    }
                    if (item.name == 'msisdn_order_month_total') {
                        item.value = genValueByType(orderTotalValue);
                    } else {
                        item.value = genValueByType(orderMakeTotalValue);
                    }
                    makeMsisdnOrderArr.push(item);
                    
                }   
            })
        })
        
    })

    let jsonTmp = JSON.stringify(makeMsisdnOrderArr)

    // fs.writeFile("makeMsisdnOrder.txt", jsonTmp, error => {
    //     if (error) throw error;
    // })
    makeMsisdnOrderArr = new Array()

    let reportTime = year + month + day + '0100' + '00';
    customConfig = {
        headers: {
            'Content-Type': 'application/json',
            'reportTime': reportTime
        }
    };
    // console.log(jsonTmp)
    const resp = await axios.post(REQ_URL, jsonTmp, customConfig);
}


/**
 * config 信息 ==================
 */

// order total
const orderTotalValue = 1000;
const orderMakeTotalValue = 800;
const year  = 2023;

// 填写具体的端节点ID，为空字符串时代表所有端节点ID
// 填写具体的省份编码，为空字符串代表所有的省份
const nodeId = "";
const provinceCode = "";
// const nodeId = "";
// const provinceCode = "";

const REQ_URL = 'http://15.116.20.124:30061/metrics/report';
// const REQ_URL = 'http://localhost:8080/metrics/report';

let makeMsisdnOrderArr = new Array();


function sleep(time) {
    return new Promise((resolve, reject) => {
        return setTimeout(resolve, time);
    });
}

let nodeList ;

async function batchSendMetricsLoop() {
    
    nodeList = await readDataFromCsv(__dirname + '/../node-server-info/en_endnode.csv');
    let days = [31,28,31,30,31,30,31,31,30,31,30,31] 
    
    ourter:
    for (let i = 0; i < days.length; i++) {
        let month = i.toString().padStart(2, '0');
        reportMonth = month;
        let day = days[i-1];
        for (let j = 1; j <= day; j++) {
            let dayStr = j.toString().padStart(2, '0');
            reportDay = dayStr;
            await batchSendMetrics(year, month, dayStr);
            // break ourter;
        }
        
    }
    reportMonth = '';
    reportDay = '';
   
}

// batchSendMetricsLoop();
let reportMonth = '';
let reportDay = '';

async function execReport() {
    if (reportMonth === '' && reportDay === '') {
        batchSendMetricsLoop();
        return 'start...'
    } else {
        return 'make msisdn order: ' + reportMonth + ", " + reportDay;
    }
}

exports.execReport = execReport;